package com.dfrz.household.controller;/*
 * @创建者：黄苟苟
 * @创建时间：2021/8/20   13:24
 * @Description描述
 **/

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dfrz.household.bean.User;
import com.dfrz.household.service.IUserService;
import com.dfrz.household.utils.Result;
import com.dfrz.household.utils.ResultUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/backuser")
public class BackendController {
    Logger logger= LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService userService;

    /**
     * AJax异步访问
     * @return
     */
    @RequestMapping("/list")
    public Result getUsers(){
        List <User> list=userService.getUsers();
        Result result= ResultUtils.success(list);
        return result;
    }
    @RequestMapping("/listparms")
    public Result getUsersParms(User user){
        logger.debug("uname="+user.getUname());
        logger.debug("Gender="+user.getGender());

        Map <String,String> parm=new HashMap <>();
        parm.put("uname",user.getUname());
        parm.put("gender",user.getGender());
        List<User> list=userService.getUsersParm(parm);
        Result result= ResultUtils.success(list);
        return result;
    }
    @RequestMapping("/listpage")
    public Result getUsersPage(String uname,Integer page,Integer limit){
        Map<String,String> parm=new HashMap<>();
        parm.put("uname",uname);
        IPage <User> p =userService.getUserByPage(parm,page,limit);
        Integer total=(int) p.getTotal();
        Result result= ResultUtils.success(p.getRecords());
        //总记录数
        result.setCount(total);
        return result;
    }

    /**
     * 转向模板页面
     * @return
     */
    @RequestMapping("/toList")
    public ModelAndView toList(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("backend_user_list");
        return mv;
    }
    /**
     * 转向模板页面
     * @return
     */
    @RequestMapping("/toAdd")
    @RequiresPermissions(value = "user")
    public ModelAndView toAdd(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("backend_user_add");
        return mv;
    }
    /**
     * 转向模板页面
     * @return
     */
    @RequestMapping("/toUpdate")
    public ModelAndView toUpdate(Integer id){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("backend_user_update");
        //根据ID取数据
        User user=userService.getUserById(id);
        mv.addObject("user",user);
        return mv;
    }
    /**
     * 转向模板页面
     * @return
     */
    @RequestMapping("/toView")
    public ModelAndView toView(Integer id){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("backend_user_view");
        //根据ID取数据
        User user=userService.getUserById(id);
        mv.addObject("user",user);
        return mv;
    }

    /**
     * 异步添加用户
     * @param user
     * @return
     */
    @RequestMapping("/add")
    public Result add(User user){
        Result result=ResultUtils.success();
        userService.save(user);
        return result;
    }
    /**
     * 异步修改用户
     * @param user
     * @return
     */
    @RequestMapping("/update")
    public Result update(User user){
        Result result=ResultUtils.success();
        userService.update(user);
        return result;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Integer id){
        Result result=null;
        try {
            userService.delete(id);
            result=ResultUtils.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 头像上传
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        Result result=null;
        System.out.println("正在执行文件上传-------------->");
        //文件名
        String filename=file.getOriginalFilename();
        //上传路径
        String filePath="D:\\springpost";
        File destFile= new File(filePath+File.separator+filename);
        System.out.println("文件："+filePath+File.separator+filename);
        try {
            //SpringMVC实现文件IO输入输出
            file.transferTo(destFile);
            Map<String,String> map=new HashMap<>();
            map.put("src",filename);
            result=ResultUtils.success(map);

        } catch (IOException e) {
            e.printStackTrace();

        }

        return result;
    }
    /**
     * 下载头像
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/downpic")
    public void downpic(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始下载>>>>>>");
        //String fileName = "qq.docx";// 文件名
        String fileName=request.getParameter("fileName");
        if (fileName != null) {
            //设置文件路径
            File file = new File("D:\\springpost\\"+fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    /**
     * 下载头像
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/downHeadPic/{filename}")
    public void downHeadPic(HttpServletRequest request, HttpServletResponse response, @PathVariable String filename) {
        System.out.println("开始下载>>>>>>");
        //String fileName = "qq.docx";// 文件名
        String fileName=filename;
        if (fileName != null) {
            //设置文件路径
            File file = new File("D:\\springpost\\"+fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

}
